package com.zzy.socket.socket_demo;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
	
	public static void main(String args[]) throws Exception {
		// 监听指定的端口
		int port = 55533;
		
		@SuppressWarnings("resource")
		ServerSocket server = new ServerSocket(port);
		// server将一直等待连接的到来
		System.out.println("服务端启动了");

		while (true) {
			Socket socket = server.accept();

			try {
				// 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
				InputStream inputStream = socket.getInputStream();
				byte[] bytes = new byte[1024];
				int len;
				StringBuilder sb = new StringBuilder();
				while ((len = inputStream.read(bytes)) != -1) {
					// 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
					sb.append(new String(bytes, 0, len, "UTF-8"));
				}
				
				System.out.println("服务端: ---  接收消息----: " + sb);

				// 给客户端返回数据
				OutputStream outputStream = socket.getOutputStream();
				String message = "你好! (信息来自服务端)";
				System.out.println("服务端:  ----发送消息---: " + message);
				socket.getOutputStream().write(message.getBytes("UTF-8"));

				inputStream.close();
				outputStream.close();
				socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}

	}
}